package com.ljfiction.book.activitys;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.icu.text.DecimalFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.liulishuo.magicprogresswidget.MagicProgressBar;
import com.ljfiction.book.Baner.MyBookEasyBean;
import com.ljfiction.book.Baner.MyMothCallDatas;
import com.ljfiction.book.Baner.MyshouruAllBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class MonthlyActivity extends BaseActivity {

    @BindView(R.id.back_monthly)
    ImageView backMonthly;
    @BindView(R.id.title_monthly)
    TextView titleMonthly;
    @BindView(R.id.allmoney)
    TextView allmoney;
    @BindView(R.id.textView3)
    TextView textView3;

    @BindView(R.id.magicprogress_monthly1)
    MagicProgressBar magicprogressMonthly1;
    @BindView(R.id.baifenbi1)
    TextView baifenbi1;
    @BindView(R.id.money1)
    TextView money1;
    @BindView(R.id.magicprogress_monthly2)
    MagicProgressBar magicprogressMonthly2;
    @BindView(R.id.baifenbi2)
    TextView baifenbi2;
    @BindView(R.id.money2)
    TextView money2;
    @BindView(R.id.magicprogress_monthly3)
    MagicProgressBar magicprogressMonthly3;
    @BindView(R.id.baifenbi3)
    TextView baifenbi3;
    @BindView(R.id.money3)
    TextView money3;
    @BindView(R.id.magicprogress_monthly4)
    MagicProgressBar magicprogressMonthly4;
    @BindView(R.id.baifenbi4)
    TextView baifenbi4;
    @BindView(R.id.money4)
    TextView money4;
    @BindView(R.id.magicprogress_monthly5)
    MagicProgressBar magicprogressMonthly5;
    @BindView(R.id.baifenbi5)
    TextView baifenbi5;
    @BindView(R.id.money5)
    TextView money5;
    @BindView(R.id.spingner_monthly)
    TextView spingnerMonthly;
    @BindView(R.id.booklist_mothly)
    RelativeLayout booklistMothly;
    @BindView(R.id.applymoney_monthly)
    SuperButton applymoneyMonthly;
    private Intent intent;
    private int year, moth, maxyear, maxmoth;//year，moth选中的年月  maxyear，maxmoth最大月报年月
    private Calendar calendar;
    private MyMothCallDatas myshouruAllBean;
    private List<MyBookEasyBean.DataBean.AlldataBean> booknamelsit = new ArrayList<>();
    private float subscription = 0, recommend = 0, giverewar = 0, disanfang = 0, kaoqin = 0, all = 0;//订阅，推荐，打赏，第三方，考勤,总和；;
    private DecimalFormat df;
    private MyBookEasyBean.DataBean.AlldataBean allBook;
    private int posistion = 0;//选中的书
    private NoBackgLodDialog noBackgLodDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monthly);
        ButterKnife.bind(this);
        AppUtils.init(this);
        calendar = Calendar.getInstance();
       booknamelsit= (List<MyBookEasyBean.DataBean.AlldataBean>) getIntent().getSerializableExtra("booknamelist");
        inttime();
        intData();
    }

    private void inttime() {
        maxyear = calendar.get(Calendar.YEAR);
        maxmoth = calendar.get(Calendar.MONTH);
        if (maxmoth == 0) {
            maxyear = maxyear - 1;
            maxmoth = 12;
        }
        year = maxyear;
        moth = maxmoth;
        textView3.setText(year + "年" + moth + "月  >");
    }

    //月报的结束月
    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/sys-getDataPosition")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                maxyear = Integer.valueOf(js.getString("data").split("-")[0]);
                                maxmoth = Integer.valueOf(js.getString("data").split("-")[1]);
                                year = maxyear;
                                moth = maxmoth;
                                textView3.setText(year + "年" + moth + "月  >");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        toAllBookManey();
                    }
                });
    }



    private void toOneBookManey(int bookId) {
        OkHttpUtils.post(HttpManager.IP + "/getAuthorMonthlyreportByBookId")

                .params("month", String.valueOf(moth))
                .params("year",  String.valueOf(year))
                .params("bookid", String.valueOf(bookId))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(MonthlyActivity.this,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                Gson gson = new Gson();
                                myshouruAllBean = gson.fromJson(jsonObject.getString("data"), MyMothCallDatas.class);
                                toIntView();
                            }else {
                                myshouruAllBean=new MyMothCallDatas();
                                toIntView();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toAllBookManey() {
        OkHttpUtils.post(HttpManager.IP + "/getAuthorMonthlyreportByAuthormonByAuthorID")

                .params("month", String.valueOf(isDan(moth)))
                .params("year",  String.valueOf(isDan(year)))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(MonthlyActivity.this,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                Gson gson = new Gson();
                                myshouruAllBean = gson.fromJson(jsonObject.getString("data"), MyMothCallDatas.class);
                                toIntView();
                            }else {
                                myshouruAllBean=new MyMothCallDatas();
                                toIntView();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private PopupWindow popupWindow;
    private RecyclerView recycleview;
    private BaseQuickAdapter mAdapter;

    private void showPopuWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.selectbook_recycle, null);
        popupWindow = new PopupWindow(contentView);
        recycleview = contentView.findViewById(R.id.selectBook_recycleview);
        recycleview.setLayoutManager(new LinearLayoutManager(this));
        recycleview.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        recycleview.setAdapter(mAdapter = new BaseQuickAdapter<MyBookEasyBean.DataBean.AlldataBean, BaseViewHolder>(R.layout.selectbook_item, booknamelsit) {
            @Override
            protected void convert(BaseViewHolder helper, MyBookEasyBean.DataBean.AlldataBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.bookName_selectitem, item.getBookName());
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                posistion = position;
                if (position == 0) {
                    if (booknamelsit.size() > 1) {
                        toAllBookManey();
                    }
                } else {
                    toOneBookManey(booknamelsit.get(position).getBookid());
                }
                spingnerMonthly.setText(booknamelsit.get(position).getBookName());
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
        //使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ScreenUtils.getScreenWidth());
        popupWindow.setHeight(ScreenUtils.getScreenHeight() * 1 / 2);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        // popupWindow.setAnimationStyle(R.style.AnimBottom);
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
        popupWindow.showAsDropDown(view);
    }

    private void toIntView() {
        subscription =myshouruAllBean.getBubscribe();
        recommend =Float.valueOf(String.format("%.2f",myshouruAllBean.getMillet()));
        giverewar = Float.valueOf(String.format("%.2f",myshouruAllBean.getPepper()));
        disanfang = Float.valueOf(String.format("%.2f",myshouruAllBean.getThirdPart()));
        kaoqin =Float.valueOf(String.format("%.2f", myshouruAllBean.getCheckworkattendance()));
        all = recommend + giverewar + subscription + disanfang + kaoqin;
        allmoney.setText(isAddDouhao(all));
        money1.setText(isAddDouhao(subscription));
        money2.setText(isAddDouhao(recommend));
        money3.setText(isAddDouhao(giverewar));
        money4.setText(isAddDouhao(disanfang));
        money5.setText(isAddDouhao(kaoqin));
        if (all == 0) {
            baifenbi1.setText("0.00%");
            baifenbi2.setText("0.00%");
            baifenbi3.setText("0.00%");
            baifenbi4.setText("0.00%");
            baifenbi5.setText("0.00%");
            magicprogressMonthly1.setPercent(0);
            magicprogressMonthly2.setPercent(0);
            magicprogressMonthly3.setPercent(0);
            magicprogressMonthly4.setPercent(0);
            magicprogressMonthly5.setPercent(0);
        } else {
            baifenbi1.setText(String.format("%.2f", (double) subscription * 100 / all) + "%");
            baifenbi2.setText(String.format("%.2f", (double) recommend * 100 / all) + "%");
            baifenbi3.setText(String.format("%.2f", (double) giverewar * 100 / all) + "%");
            baifenbi4.setText(String.format("%.2f", (double) disanfang * 100 / all) + "%");
            baifenbi5.setText(String.format("%.2f", (double) kaoqin * 100 / all) + "%");
            magicprogressMonthly1.setPercent((float) subscription / all);
            magicprogressMonthly2.setPercent((float) recommend / all);
            magicprogressMonthly3.setPercent((float) giverewar / all);
            magicprogressMonthly4.setPercent((float) disanfang / all);
            magicprogressMonthly5.setPercent((float) kaoqin / all);
        }


    }

    @OnClick({R.id.back_monthly, R.id.textView3, R.id.booklist_mothly,R.id.applymoney_monthly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_monthly:
                goBack();
                break;
            case R.id.textView3:
                intent = new Intent(MonthlyActivity.this, MothActivity.class);
                intent.putExtra("maxyear", maxyear);
                intent.putExtra("maxmoth", maxmoth);
                startActivityForResult(intent, 1);
                break;
            case R.id.booklist_mothly:
                if (booknamelsit.size() < 2) {
                    showToast("还没有书籍");
                } else {
                    if (popupWindow != null && !popupWindow.isShowing()) {
                        popupWindow.showAsDropDown(view);
                    } else {
                        showPopuWindow(view);
                    }
                }
                break;
            case R.id.applymoney_monthly:
                intent=new Intent(MonthlyActivity.this,ApplymoneyActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2 && requestCode == 1) {
            year = data.getIntExtra("year", 2018);
            moth = data.getIntExtra("moth", 1);
            textView3.setText(year + "年" + moth + "月  >");
            if (posistion == 0 && booknamelsit.size() > 1) {
                toAllBookManey();
            } else if (posistion > 0) {
                toOneBookManey(booknamelsit.get(posistion).getBookid());
            }
        }
    }

    private String isDan(int dan) {
        if (dan < 10) {
            return "0" + String.valueOf(dan);
        } else {
            return String.valueOf(dan);
        }
    }

    private String isAddDouhao(float num) {
        BigDecimal bigDecimal=new BigDecimal(num);
        return String.valueOf(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());

    }
}
